import React, {Component} from "react";

export default function withData(WrappedComponent, data) {
  return class extends Component {
    constructor (props) {
      super(props)
      this.state = {
        isAlive: true,
        // 初始尺寸
        height: 1,
        width: 2,
        ...props,
        ...data,
      }
      this.timer = null
      this.className = props.className ?? ''
      // 生长系数
      this.growIndex = Math.random() + 1
      // 生长间隔时间
      this.growTimes = props.growTimes ?? 5000
      // 最多生长次数
      this.maxTimes = props.maxTimes ?? 10
    }
    componentDidMount () {
      this.timer = setInterval(this.RootGrow, this.growTimes / (this.props.speed ?? 1))
    }
    componentDidUpdate (props) {
      clearInterval(this.timer)
      this.timer = setInterval(this.RootGrow, this.growTimes / (props.speed ?? 1))
    }
    componentWillUnmount () {
      clearInterval(this.timer)
    }
    // 树根生长
    RootGrow = () => {
      if (this.state.isAlive && this.maxTimes > 0) {
        // console.log('树根长大了')
        this.setState({
          height: this.state.height + this.growIndex,
          width: this.state.width + 1.5 * this.growIndex,
        })
        this.maxTimes--
      } else {
        clearInterval(this.timer)
      }
    }
    render() {
      const newProps = Object.assign({}, this.props, {
        ...this.state
      })
      return <WrappedComponent {...newProps}></WrappedComponent>
    }
  }
}